//
//  JBWComposeView.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/7.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit
import pop
class JBWComposeView: UIView {

    //记录父控件
    var target: UIViewController?
    //自定义保存按钮
    lazy var composeButtonList: [JBWComposeButton] = [JBWComposeButton]()
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //类方法显示当前的view
    class func show(target: UIViewController){
        let composeView = JBWComposeView()
        //赋值
        composeView.target = target
        target.view.addSubview(composeView)
        
        //6个按钮的弹簧动画
        composeView.setupComposeButtonAnim(isUp: true)
    }
    //设置视图
    private func setupUI(){
       backgroundColor = randomColor()
        
        //添加控件
        addSubview(bgImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        addComposeButtons()
    
    }
    //懒加载控件
    //背景图片
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenSnap()!.applyLightEffect())
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        removeFromSuperview()
        setupComposeButtonAnim(isUp: false)
        //延迟删除当前界面
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.removeFromSuperview()
            
        }
    }
}

extension JBWComposeView {
    //添加composeButton
    fileprivate func addComposeButtons(){
        
        //获取plist模型数组
        let composeList = loadComposePlist()
        //计算按钮的宽和高
        let composeButtonW: CGFloat = 80
        let composeButtonH: CGFloat = 110
        //间距
        let composeMargin  = (JBWSCREENW - composeButtonW * 3) / 4
        //循环创建六次
        for (i, composeModel) in composeList.enumerated() {
            //计算行和列索引
            let row = CGFloat(i/3)
            let col = CGFloat(i%3)
            //创建按钮
            let button = JBWComposeButton()
            //赋值
            button.composeModel = composeModel
            //添加监听事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            button.frame = CGRect(x:composeMargin + (composeMargin + composeButtonW)*col, y: JBWSCREENH + (composeMargin + composeButtonH)*row, width: composeButtonW, height: composeButtonH)
            button.setImage(UIImage(named: composeModel.icon ?? ""), for: UIControlState.normal)
            button.setTitle(composeModel.title, for: UIControlState.normal)
            addSubview(button)
            
            //添加
            composeButtonList.append(button)
            
        }
        
    }
}

extension JBWComposeView {
    
    //监听事件
    @objc fileprivate func buttonClick(composeButton: JBWComposeButton){
        
        //设置动画
        UIView.animate(withDuration: 0.25, animations: { 
            //遍历按钮数组
            for button in self.composeButtonList {
                button.alpha = 0.2
                //点击按钮
                if button == composeButton {
                    //放大
                    composeButton.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //缩小
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }

        }) { (_) in
            
            //动画完成恢复原样
            UIView.animate(withDuration: 0.25, animations: { 
                //遍历按钮恢复原状
                for button in self.composeButtonList {
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
          
            
        },completion: { (_) in
            
            //判断className是否为nil
            guard let className = composeButton.composeModel?.className else {
                return
            }
            //判断是否为nil 且是否可以转成UIViewController.type
            guard let type = NSClassFromString(className) as? UIViewController.Type else {
                return
            }
            //通过anyclass创建一个对象
            let vc = type.init()
            //创建导航控制器
            let nav = JBWNavigationController(rootViewController: vc)
            //模态形式弹出
            self.target?.present(nav, animated: true, completion: { 
                //移除
                self.removeFromSuperview()
            })
        })
    
}
}
}
extension JBWComposeView {
    //设置弹簧动画
    fileprivate func setupComposeButtonAnim(isUp: Bool){
        
        var buttonMargin: CGFloat = -350
        //消失动画
        if !isUp {
            buttonMargin = 350
            composeButtonList = composeButtonList.reversed()
        }
        
        //遍历按钮
        for (i, composeButton)in composeButtonList.enumerated(){
            let anSprinng = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            anSprinng?.toValue = CGPoint(x: composeButton.center.x, y: composeButton.center.y + buttonMargin)
            anSprinng?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //弹簧系数
            anSprinng?.springBounciness = 10
            composeButton.pop_add(anSprinng, forKey: nil)
        }
    }
}
extension JBWComposeView {
    
    //去取plist文件
    fileprivate func loadComposePlist() -> [JBWComposeModel] {
        //路径
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let plistArray = NSArray(contentsOfFile: file)!
        let tempList = NSArray.yy_modelArray(with: JBWComposeModel.self, json: plistArray) as! [JBWComposeModel]
        return tempList
    }
}
